<template>
  <div id="app" class="ancient-theme" :class="{ narrow: isNarrow }">
    <!-- 宽屏：保留原来的顶部导航 -->
    <header v-if="!isNarrow" class="app-header" :class="{ 'is-scrolled': scrolled }">
      <div class="nav-left">
        <div class="logo" @click="$router.push('/')">AncientSeeker</div>
        <el-menu mode="horizontal" :default-active="$route.path" router class="main-menu">
          <el-menu-item index="/"><el-icon><House /></el-icon><span>首页</span></el-menu-item>
          <el-menu-item index="/library"><el-icon><Reading /></el-icon><span>典籍库</span></el-menu-item>
          <el-menu-item index="/chat"><el-icon><ChatDotRound /></el-icon><span>AI对话</span></el-menu-item>
          <el-menu-item index="/image"><el-icon><Picture /></el-icon><span>AI绘图</span></el-menu-item>
          <el-sub-menu index="/explore">
            <template #title>
              <el-icon><Compass /></el-icon><span>探索模式</span>
            </template>
            <el-menu-item index="/explore">节点与任务</el-menu-item>
            <el-menu-item index="/explore/achievements">成就</el-menu-item>
            <el-menu-item index="/explore/graph">图谱</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="/profile"><el-icon><User /></el-icon><span>个人中心</span></el-menu-item>
          <el-menu-item index="/about"><el-icon><InfoFilled /></el-icon><span>关于</span></el-menu-item>
        </el-menu>
      </div>
      <div class="nav-right">
        <UserMenu :user="user" @login="authVisible=true" @logout="onLogout" />
      </div>
    </header>

    <!-- 窄屏：顶部精简条 + 侧边抽屉（默认隐藏 -->
    <div v-else class="mobile-topbar" :class="{ 'is-scrolled': scrolled }">
      <button class="hamburger" @click="toggleDrawer" aria-label="切换导航" :aria-expanded="mobileOpen">
        <span class="line" /><span class="line" /><span class="line" />
      </button>
      <div class="m-title" @click="$router.push('/')">AncientSeeker</div>
      <div class="m-user">
        <UserMenu :user="user" @login="authVisible=true" @logout="onLogout" compact />
      </div>
    </div>

    <transition name="fade-fast">
      <div v-if="isNarrow && mobileOpen" class="mobile-overlay" @click="closeDrawer" />
    </transition>

    <transition name="slide-left">
      <nav
        v-if="isNarrow && mobileOpen"
        class="mobile-drawer"
        aria-label="主导航"
      >
        <div class="drawer-head">
          <div class="drawer-logo" @click="$router.push('/')">AncientSeeker</div>
          <button class="close-btn" @click="closeDrawer" aria-label="关闭导航">
            <el-icon><Close /></el-icon>
          </button>
        </div>
        <el-menu
          mode="vertical"
          :default-active="$route.path"
          router
          class="drawer-menu"
          @select="closeDrawer"
        >
          <el-menu-item index="/"><el-icon><House /></el-icon><span>首页</span></el-menu-item>
          <el-menu-item index="/library"><el-icon><Reading /></el-icon><span>典籍库</span></el-menu-item>
          <el-menu-item index="/chat"><el-icon><ChatDotRound /></el-icon><span>AI对话</span></el-menu-item>
          <el-menu-item index="/image"><el-icon><Picture /></el-icon><span>AI绘图</span></el-menu-item>
          <el-sub-menu index="/m/explore">
            <template #title>
              <el-icon><Compass /></el-icon><span>探索模式</span>
            </template>
            <el-menu-item index="/explore">节点与任务</el-menu-item>
            <el-menu-item index="/explore/achievements">成就</el-menu-item>
            <el-menu-item index="/explore/graph">图谱</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="/profile"><el-icon><User /></el-icon><span>个人中心</span></el-menu-item>
          <el-menu-item index="/about"><el-icon><InfoFilled /></el-icon><span>关于</span></el-menu-item>
        </el-menu>
        <div class="drawer-footer">
          <UserMenu :user="user" @login="authVisible=true" @logout="onLogout" compact />
        </div>
      </nav>
    </transition>

    <AuthModal :visible="authVisible" @close="authVisible=false" @login-success="onLoginSuccess" />
    <main class="main-content" :class="{ 'with-topbar': !isNarrow, 'with-mobilebar': isNarrow, 'full-width': $route.meta.fullWidth }">
      <router-view />
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { authApi } from '@/api/http'
import { useRoute } from 'vue-router'
import AuthModal from '@/components/common/AuthModal.vue'
import UserMenu from '@/components/common/UserMenu.vue'
import { STORAGE_TOKEN_KEY, getToken, removeToken } from '@/utils/auth'

const route = useRoute()
const user = ref(null)
const authVisible = ref(false)
const scrolled = ref(false)
const isNarrow = ref(false)
const mobileOpen = ref(false)

const evaluateNarrow = () => {
  // 使用更宽松阈值 + 多源判定，解决某些手机 UA 默认 980/1024 宽度导致判定为桌面的问题
  const vw = document.documentElement.clientWidth || window.innerWidth
  const coarse = window.matchMedia && window.matchMedia('(pointer: coarse)').matches
  // 逻辑：视口 < 1100 直接判定；或指针为粗略并且宽度 < 1400 也判定（防止大平板横屏）
  isNarrow.value = vw < 1100 || (coarse && vw < 1400)
  if (!isNarrow.value) mobileOpen.value = false
}
const handleResize = () => { evaluateNarrow() }

function toggleDrawer() { mobileOpen.value = !mobileOpen.value }
function closeDrawer() { mobileOpen.value = false }

const loadUser = async () => {
  const token = getToken()
  if (!token) { user.value = null; return }
  try {
    const res = await authApi.me()
    user.value = res.data
  } catch {
    removeToken(); user.value = null
  }
}

const onLoginSuccess = (u) => { user.value = u; window.dispatchEvent(new CustomEvent('auth-login')) }
const onLogout = () => { removeToken(); user.value = null; window.dispatchEvent(new CustomEvent('auth-logout')) }

const handleScroll = () => { scrolled.value = window.scrollY > 8 }
onMounted(() => {
  loadUser();
  evaluateNarrow();
  window.addEventListener('scroll', handleScroll, { passive: true });
  window.addEventListener('resize', handleResize, { passive: true });
  // 监听 token 过期事件，自动重置用户并弹出登录框（可选触发）
  window.addEventListener('auth-expired', () => { user.value = null; authVisible.value = true })
})
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('auth-expired', () => {})
})
</script>

<style lang="scss">
@import '@/assets/styles/variables.scss';

$header-height: 60px;
$drawer-width: 230px;

#app {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
    'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial,
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  min-height: 100vh;
  /* 分层水墨+宣纸质感背景 */
  background:
    radial-gradient(circle at 20% 15%, rgba(255,255,255,0.55) 0%, rgba(255,255,255,0) 60%),
    linear-gradient(125deg, #f8f9fb 0%, #eef2f7 40%, #e3e8ef 70%, #d9dee5 100%),
    repeating-linear-gradient(45deg, rgba(255,255,255,0.25) 0 8px, rgba(0,0,0,0.02) 8px 16px);
  background-blend-mode: screen, normal, multiply;
}

 .app-header { 
  position: sticky; top: 0; z-index: $z-index-fixed; 
  display:flex; align-items:center; justify-content:space-between; 
  backdrop-filter: blur(14px) saturate(180%);
  background: linear-gradient(90deg, rgba(255,255,255,0.82), rgba(255,255,255,0.72));
  padding: 0 20px; border-bottom:1px solid rgba(255,255,255,0.4);
  height: $header-height; transition: box-shadow $duration-base $ease-in-out, background $duration-base $ease-in-out;
 }
 .app-header.is-scrolled { box-shadow: 0 4px 18px -4px rgba(0,0,0,0.12); background: rgba(255,255,255,0.92); }
 .nav-left { display:flex; align-items:center; flex: 1; }
 .logo { font-weight:600; font-size:20px; letter-spacing:.5px; margin-right:14px; cursor:pointer; 
   background:linear-gradient(100deg,#c8102e,#e8576b 45%, #f4a261 85%); -webkit-background-clip:text; background-clip:text; color:transparent;
   position: relative;
 }
 /* 移除横线强调，保持简洁品牌展示 */
 .main-menu { background:transparent; border-bottom:none; --el-menu-active-color: #c8102e; flex: 1; }
 /* 禁用 Element Plus 菜单的自动折叠功能 */
 .main-menu :deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__icon-arrow) { display: block; }
 .main-menu :deep(.el-menu--horizontal.el-menu) { display: flex !important; }
 .main-menu :deep(.el-menu--horizontal > .el-menu-item),
 .main-menu :deep(.el-menu--horizontal > .el-sub-menu) { display: flex !important; }
 .main-menu :deep(.el-menu-item) { font-weight:500; padding: 0 16px; }
 .main-menu :deep(.el-sub-menu) { padding: 0 4px; }
 .main-menu :deep(.el-menu-item.is-active) { 
   background: linear-gradient(140deg, rgba(200,16,46,0.12), rgba(244,162,97,0.18));
   border-radius: 10px; 
 }
 .main-menu :deep(.el-menu-item:not(.is-active):hover) { background: rgba(255,255,255,0.6); border-radius:10px; }
 .nav-right { display:flex; align-items:center; gap:12px; }

 .main-content { width:100%; max-width:1360px; margin:0 auto; animation: fadeIn .6s $ease-out; }
 .main-content.full-width { max-width:none; width:100%; margin:0; padding-left:0; padding-right:0; }
 /* 统一所有桌面页面顶部间距 = header 高度 + 4px */
 .main-content.with-topbar { padding: $header-height 22px 38px; padding-top: calc($header-height + 4px); min-height: calc(100vh - $header-height); }
 /* 全宽页面保持相同顶部规则，仅调整左右内边距 */
 .main-content.full-width.with-topbar { padding-top: calc($header-height + 4px); }
  /* 所有页面：当元素类名包含 -page（即页面根容器），无论后面是否附加其他类（如 collapsed），均贴近导航 */
  .main-content.with-topbar > [class*='-page'] { margin-top: calc(-1 * ($header-height + 4px)); }
  @media (max-width:1100px){
    .main-content.with-topbar > [class$='-page'] { margin-top:0; }
  }
 /* 移除 AIChat 单独负 margin，保持一致性 */
 /* 移动端顶部也同步缩小：原 16px -> 4px */
 .main-content.with-mobilebar { padding: calc(52px + 4px) 12px 48px; min-height:100vh; }
 @media (min-width:1600px){
   .main-content.with-topbar { padding-left:26px; padding-right:26px; }
 }

/* 窄屏顶部条 */
.mobile-topbar { position:fixed; top:0; left:0; right:0; height:52px; display:flex; align-items:center; padding:0 12px 0 8px; background:linear-gradient(90deg, rgba(255,255,255,0.9), rgba(255,255,255,0.78)); backdrop-filter:blur(14px) saturate(170%); border-bottom:1px solid rgba(0,0,0,0.05); z-index:$z-index-fixed; }
.mobile-topbar.is-scrolled { box-shadow:0 4px 14px -6px rgba(0,0,0,0.15); }
.hamburger { width:40px; height:40px; border:none; background:transparent; display:flex; flex-direction:column; justify-content:center; gap:5px; padding:0 10px; cursor:pointer; }
.hamburger .line { width:20px; height:2px; background:#2c3e50; border-radius:2px; transition: transform .3s ease; }
.m-title { font-size:18px; font-weight:600; letter-spacing:1px; background:linear-gradient(100deg,#c8102e,#e8576b 45%, #f4a261 85%); -webkit-background-clip:text; background-clip:text; color:transparent; cursor:pointer; }
.m-user { margin-left:auto; display:flex; align-items:center; }

/* 抽屉 */
.mobile-drawer { position:fixed; top:0; left:0; bottom:0; width:$drawer-width; background:linear-gradient(180deg, rgba(255,255,255,0.96), rgba(255,255,255,0.86)); backdrop-filter:blur(16px) saturate(180%); border-right:1px solid rgba(0,0,0,0.08); z-index: calc($z-index-fixed + 2); display:flex; flex-direction:column; padding:14px 14px 18px; box-shadow:4px 0 18px -6px rgba(0,0,0,0.22); }
.drawer-head { display:flex; align-items:center; gap:8px; margin-bottom:8px; }
.drawer-logo { font-weight:600; font-size:20px; letter-spacing:1px; background:linear-gradient(100deg,#c8102e,#e8576b 45%, #f4a261 85%); -webkit-background-clip:text; background-clip:text; color:transparent; flex:1; cursor:pointer; }
.close-btn { background:rgba(255,255,255,0.7); border:1px solid rgba(0,0,0,0.08); width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; cursor:pointer; }
.drawer-menu { flex:1; background:transparent; }
.drawer-menu :deep(.el-menu-item) { height:46px; line-height:46px; border-radius:10px; margin-bottom:2px; font-weight:500; }
.drawer-menu :deep(.el-menu-item.is-active) { background:linear-gradient(145deg, rgba(200,16,46,0.14), rgba(244,162,97,0.22)); }
.drawer-menu :deep(.el-menu-item:not(.is-active):hover) { background:rgba(255,255,255,0.7); }
.drawer-footer { padding-top:12px; border-top:1px dashed rgba(0,0,0,0.1); }

/* 遮罩 */
.mobile-overlay { position:fixed; inset:0; background:rgba(0,0,0,0.38); backdrop-filter: blur(2px); z-index: calc($z-index-fixed + 1); }

/* 过渡 */
.slide-left-enter-active, .slide-left-leave-active { transition: transform .35s cubic-bezier(.4,.0,.2,1), opacity .35s; }
.slide-left-enter-from, .slide-left-leave-to { transform: translateX(-110%); opacity:0; }
.fade-fast-enter-active, .fade-fast-leave-active { transition: opacity .25s ease; }
.fade-fast-enter-from, .fade-fast-leave-to { opacity:0; }

@media (max-width: 420px) {
  .drawer-logo { font-size:18px; }
  .drawer-menu :deep(.el-menu-item){ height:44px; }
  .mobile-drawer { width:210px; }
}

/* 移除旧 rail 样式，保留简化双状态方案 */

@keyframes fadeIn { from { opacity:0; transform: translateY(8px);} to { opacity:1; transform:none; } }

body {
  margin: 0;
  padding: 0;
}

* { box-sizing: border-box; }

/* 主题可扩展挂钩 */
.ancient-theme {
  --as-color-primary: #c8102e;
  --as-color-accent: #264653;
  --as-panel-bg: rgba(255,255,255,0.72);
  --as-border-soft: rgba(0,0,0,0.06);
}

/* 可后续用于卡片统一风格（示例占位，不影响现有 ElementPlus） */
.as-panel { background: var(--as-panel-bg); backdrop-filter: blur(12px); border:1px solid var(--as-border-soft); border-radius: 16px; padding:20px; }
</style>